//
//  SZAccountViewModel.m
//  Weibo
//
//  Created by Zahi on 2017/7/26.
//  Copyright © 2017年 Zahi. All rights reserved.
//

#import "SZAccountViewModel.h"
#import "SZNetworkTools.h"
#import "SZUserAccount.h"

@implementation SZAccountViewModel
#pragma mark - 账户VM单例对象
+ (instancetype)shared
{
    static id instance;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        instance = [SZAccountViewModel new];
    });
    
    return instance;
}

#pragma mark - init
- (instancetype)init
{
    if (self = [super init]) {
        
        // 从沙盒中解档用户信息
        self.account = [SZUserAccount readAccount];
    }
    return self;
}


/// 是否登录过
- (BOOL)isLogin
{
    return [self accessToken];
}


/// 判断令牌是否过期
- (NSString *)accessToken
{
    NSString *token = self.account.access_token;
    
    if (token != nil) {//有值
        NSComparisonResult result = [self.account.expiersDate compare:[NSDate date]];
        
        if (result == NSOrderedDescending) {// 降序 '过期时间' > '当前时间'-->没有过期
            return token;
        }
    }
    return nil;
    
}


#pragma mark 获取令牌

- (void)obtainAccessTokenWithCode:(NSString *)code callBack:(void(^)(BOOL isOK))callBack
{
    [SZNetworkTools.sharedTool accessTokenWithCode:code callBack:^(id responce, NSError *error) {
        
        if (error != nil) { // 网络出错
            NSLog(@"%@",error);
            callBack(NO);
            return;
        } else {
            
            NSDictionary *dict = responce;
            
            // 字典转模型
            SZUserAccount *account = [SZUserAccount accountWithDict:dict];
            
            // 获取用户信息
            [self obtainUserInfo:account completion:callBack];
        }
    }];
}

#pragma mark - 获取用户信息
- (void)obtainUserInfo:(SZUserAccount *)account completion:(void(^)(BOOL isOK))completion
{
    
    NSString *token = account.access_token;
    NSInteger uid = account.uid;
    
    [SZNetworkTools.sharedTool accoundInfoWithToken:token uid:uid callBack:^(id responce, NSError *error) {
        
        if (error != nil) {
            NSLog(@"%@",error);
            completion(NO);
            return;
        } else { //登录成功
            NSDictionary *dict = responce;
            account.name = dict[@"name"];
            account.avatar_large = dict[@"avatar_large"];
            
            // 登录成功 保存用户对象
            [account saveAccount];
            
            // 记录用户模型
            self.account = account;

            completion(YES);
        
        }
        
    }];
    
}



@end
